import React from 'react';
import Carousel from 'antd-mobile/lib/carousel';
import Menu from 'shared/components/Menu';
import HeaderNav from 'shared/components/HeaderNav';
import SecondMenu from 'shared/components/SecondMenu';
import { fetchCategoryList, appid } from 'shared/api';
import localStorage from 'shared/utils/localStorage';
import getUrlParam from 'shared/utils/getUrlParam';
import callWeixinJSbridge from 'shared/utils/callWeixinJSbridge';
import { fetchBannerList } from './api';
import PromotionList from './PromotionList';
import HomeCategoryProductlist from './HomeCategoryProductlist';
import HomereCommendList from './HomereCommendList';
import FriendLink from './FriendLink';
import Activity from './activity';
import './index.less';

const REDIRECT_URI = encodeURI(`${location.origin}${location.pathname}`);
const urlApi = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`

export default class Home extends React.PureComponent {
  state = {
    data: [],
    filterCategoryItem: null,
    categoryList: [],
    showSecondMenu: false,
    top:false
  }

  constructor(props) {
    super(props);

    if (getUrlParam('redirect_url') === 'checkPayStatus') {
      __self.history.push('/checkPayStatus')
    }

    localStorage.set('wxCode', '')
  }

  componentDidMount() {
    callWeixinJSbridge(this.weixin)
    fetchBannerList().then(({ data }) => {
      this.setState({ data })
    })
    fetchCategoryList().then(({ data }) => {
      this.setState({ categoryList: data })
    })

    window.addEventListener('scroll', this.scrollListen, false);

  }

  componentWillUnmount(){
    window.removeEventListener('scroll',this.scrollListen,false);
  }

  scrollListen = () => {
    if(window.scrollY > 600){
      this.setState({top:true});
    }else{
      this.setState({top:false});
    }
  }

  weixin = () => {
    if (!getUrlParam('code')) {
      location.href = urlApi;
      return;
    }
    localStorage.set('wxCode', getUrlParam('code'))
  }

  handleOnFilterCategory = (item) => {
    this.setState({ filterCategoryItem: item });
  }

  handleOpenMenu = () => {
    this.setState({ showSecondMenu: true });
  }

  handleCloseMenu = () => {
    this.setState({ showSecondMenu: false });
  }

  handleMenuItemClick = (item) => {
    gloablMonitor(['首页-产品分类', item.title])
    __self.history.push(`/allProduct?defaultCategoryId=${item.category_id}`)
  }

  render() {
    const { filterCategoryItem, categoryList, showSecondMenu, top } = this.state;
    return (
      [
        <HeaderNav key="HeaderNav" showBackLink={false} onMenuButton={this.handleOpenMenu}  />,
        <SecondMenu
          key="SecondMenu"
          data={categoryList}
          show={showSecondMenu}
          onClose={this.handleCloseMenu}
          onItemClick={this.handleMenuItemClick}
        />,
        (
          <div className="home" key="home">
            <Carousel
              autoplay={false}
              infinite
            >
              {this.state.data.map((item, index) => (
                <a
                  href={+item.banner_image_id !== 11814 ? item.linkmobile : 'javascript:void(0);'}
                  target={+item.banner_image_id !== 11814 ? '_blank' : '_self'}
                  key={index}
                  style={{ display: 'inline-block', width: '100%' }}
                  onClick={() => { gloablMonitor(['首页-活动', item.title]) }}
                >
                  <img
                    src={item.image}
                    alt={item.title}
                    style={{ width: '100%', verticalAlign: 'top'}}
                  />
                </a>
              ))}
            </Carousel>
            <div className="nav-black">
              <Activity history={this.props.history} />
              <PromotionList />
              <HomeCategoryProductlist filterCategoryItem={filterCategoryItem} />
              <HomereCommendList />
              <FriendLink />
              {
                top ? <a id="toTop" href="#">返回顶部</a> : null
              }
            </div>
          </div>
        ),
        <Menu key="menu" />
      ]
    )
  }
}